package com.xy.sdk.share;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
//import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static android.content.ContentValues.TAG;
import static com.xy.sdk.share.ShareConstants.QQAPP_AUTHORITIES;

import androidx.core.content.FileProvider;


/**
 * 原生分享
 * Craeted by tianshen
 * Created on 2021/4/25
 */
public class NativeShare {

    public static final String PACKAGE_WECHAT = "com.tencent.mm";
    public static final String PACKAGE_MOBILE_QQ = "com.tencent.mobileqq";
    public static final String PACKAGE_QZONE = "com.qzone";
    public static final String PACKAGE_SINA = "com.sina.weibo";

    public static final String AUTHORITY = "com.share.gudd.fileprovider";


    /**
     * 分享图片给QQ好友
     *
     * @param path
     */
    public static void shareImageToQQ(Context mContext, String path, ShareCallback callback) {
        String app_auhoritprities;
        app_auhoritprities = getAuthority(mContext);
        if (TextUtils.isEmpty(app_auhoritprities)) {
            app_auhoritprities = mContext.getPackageName() + QQAPP_AUTHORITIES;
            Log.e("XYSDK", "TextUtils.isEmpty app_auhoritprities :" +
                    app_auhoritprities);
        }
        Log.e("XYSDK", "shareImageToQQ:" + path);
        File picFile = new File(path);
        if (isInstallApp(mContext, PACKAGE_MOBILE_QQ)) {
            try {
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(mContext, app_auhoritprities, picFile);
                } else {
                    uri = Uri.fromFile(picFile);
                }
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                shareIntent.setType("image/*");
                // 遍历所有支持发送图片的应用。找到需要的应用
                ComponentName componentName = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");

                shareIntent.setComponent(componentName);
                mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
                callback.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("XYSDK", "share 分享图片到qq失败");
            }
        } else {
            Toast.makeText(mContext, "您需要安装QQ客户端", Toast.LENGTH_LONG).show();

        }
    }


    /**
     * 直接分享图片到微信好友
     *
     * @param context
     * @param path
     */
    public static void shareWX(Context context, String path, ShareCallback callback) {
        try {
            if (isInstallApp(context, PACKAGE_WECHAT)) {
                String app_auhoritprities = getAuthority(context);
                if (TextUtils.isEmpty(app_auhoritprities)) {
                    app_auhoritprities = context.getPackageName() + QQAPP_AUTHORITIES;
                    Log.e("XYSDK", "TextUtils.isEmpty(app_auhoritprities)");
                }

                File picFile = new File(path);
                Intent intent = new Intent();
                ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                intent.setComponent(cop);
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("image/*");
                ApplicationInfo applicationInfo = context.getApplicationInfo();
                int targetSDK = applicationInfo.targetSdkVersion;
                if (picFile != null) {
                    if (picFile.isFile() && picFile.exists()) {
                        Uri uri;
                        if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                            try {
                                uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), picFile.getAbsolutePath(), "游戏分享" + System.currentTimeMillis(), null));
                            } catch (Exception e) {
                                e.printStackTrace();
                                uri = FileProvider.getUriForFile(context, app_auhoritprities, picFile);
                            }

                        } else {
                            uri = Uri.fromFile(picFile);
                        }
                        intent.putExtra(Intent.EXTRA_STREAM, uri);
                    }
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(Intent.createChooser(intent, "Share"));
                callback.onComplete();
            } else {
                Toast.makeText(context, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 原生微博分享
     *
     * @param context
     * @param photoPath
     * @param callback
     */
    public static void shareToWeibo(Context context, String photoPath, ShareCallback callback) {
        try {
            String app_auhoritprities = getAuthority(context);
            if (TextUtils.isEmpty(app_auhoritprities)) {
                app_auhoritprities = context.getPackageName() + QQAPP_AUTHORITIES;
                Log.e("XYSDK", "TextUtils.isEmpty(app_auhoritprities)");
            }
            if (isInstallApp(context, PACKAGE_SINA)) {
                File file = new File(photoPath);
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");// 分享文本|文本+图片|图片 到微博内容时使用
                intent.setClassName(PACKAGE_SINA, "com.sina.weibo.composerinde.ComposerDispatchActivity");// 这里在使用resolveInfo的时候需要做判空处理防止crash

                if (file.isFile() && file.exists()) {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = FileProvider.getUriForFile(context, app_auhoritprities, file);
                    } else {
                        uri = Uri.fromFile(file);
                    }
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                }
                context.startActivity(intent);
                callback.onComplete();
            } else {
                Toast.makeText(context, "您需要安装微博客户端", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {

        }
    }


    /**
     * 保存到相册
     *
     * @param context
     * @param path
     * @return
     */
    public static boolean saveImageToGallery(Context context, String path) {
        Bitmap bmp = BitmapFactory.decodeFile(path);

        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                File.separator + "xyyou_share";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "xyyou_share" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
//            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            Toast.makeText(context, "保存截图成功", Toast.LENGTH_LONG).show();
            return isSuccess;
        } catch (Exception e) {
            Toast.makeText(context, "保存截图失败，请手动截图", Toast.LENGTH_LONG).show();

            e.printStackTrace();

            return false;
        }
    }


    // 判断是否安装指定app
    public static boolean isInstallApp(Context context, String packageName) {
        Log.e(TAG, "isInstallApp:"+packageName);
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "包名不存在，应用未安装");
            e.printStackTrace();
            return false; // 包名不存在，应用未安装
        } catch (Exception e) {
            Log.e(TAG, "其他异常");
            e.printStackTrace();
            return false; // 其他异常
        }
    }

    public static String getAuthority(Context context) {
        try {


            String packageName = context.getPackageName();
            PackageInfo info = null;
            try {
                info = context.getPackageManager().getPackageInfo(packageName,
                        PackageManager.GET_PROVIDERS);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            ProviderInfo[] providers = info.providers;
            for (ProviderInfo provider : providers) {
                Log.e(TAG, "name is " + provider.name);
                if (provider.name.equals("android.support.v4.content.FileProvider")) {
                    Log.e(TAG, "authority is " + provider.authority);
                    if (provider.authority != null) {
                        return provider.authority;
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
